package bgw

import (
	"context"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bgw"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type BgwPayoutNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// stanpayng提现回调通知
func NewBgwPayoutNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BgwPayoutNotifyLogic {
	return &BgwPayoutNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BgwPayoutNotifyLogic) BgwPayoutNotify(_header http.Header, req *types.BgwWithdrawCallbackRequest, body []byte) (resp string, err error) {
	order, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawListPage(l.ctx, &rpc.FindWithDrawReq{OrderNo: req.OuterNo})
	if err != nil {
		return
	}
	if len(order.Data) == 0 {
		logc.Error(l.ctx, "order.Data does not exist", string(body))
		err = assets.ErrWithdrawPayNoChannel
		return
	}
	_channel, ok := order.Data[0].Channel[order.Data[0].WithdrawChannelId]
	if !ok || _channel == nil {
		logc.Error(l.ctx, "order.Data[0].Channel[order.Data[0].WithdrawChannelId] does not exist", string(body))
		err = assets.ErrWithdrawPayNoChannel
		return
	}
	secret := _channel.SecretKey
	logc.Info(l.ctx, "bgw Channel:", _channel)
	callBackResponse, err := bgw.NewWithdrawService(_channel.MerchantId, _channel.AppId, _channel.AppCode, secret).WithdrawCallbackVerify(_header, body)
	if err != nil {
		logc.Error(l.ctx, err)
		return
	}
	// 根据订单状态处理业务逻辑
	switch callBackResponse.Status {
	case 0, 1, 2, 3, 4: // 发起提款，订单已经创建
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawSuccess(l.ctx, &rpc.SuccessWithDrawReq{OrderNo: callBackResponse.OuterNo, Data: string(body)})
	// case 1: // 商户已确认
	// case 2: // 财务已确认
	// case 3: // 转出确认中
	// case 4: // 确认转出
	case 5: // 提款驳回
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawFail(l.ctx, &rpc.FailWithDrawReq{OrderNo: callBackResponse.OuterNo, Data: string(body), Err: callBackResponse.RejectReason})
	}
	if err != nil {
		logc.Error(l.ctx, err, string(body))
	}
	return
}
